package com.lianjinsu.shop.core.helper;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

import java.util.Objects;
import java.util.function.Supplier;

public class SpringEnvironmentHelper extends ApplicationObjectSupport {
    private static volatile ConfigurableEnvironment configurableEnvironment;

    public static <T> T getValue(String key, Class<T> cls) {
        return configurableEnvironment.getProperty(key, cls);
    }

    public static <T> T getValue(String key, Class<T> cls, T devValue) {
        return configurableEnvironment.getProperty(key, cls, devValue);
    }

    public static <T> T getValue(String key, Class<T> cls, Supplier<T> devValue) {
        return configurableEnvironment.getProperty(key, cls, devValue.get());
    }

    public static String getValue(String key) {
        return configurableEnvironment.getProperty(key);
    }

    public static String getValue(String key, String defValue) {
        return configurableEnvironment.getProperty(key, defValue);
    }

    public static String getValue(String key, Supplier<String> defValueSupplier) {
        return configurableEnvironment.getProperty(key, defValueSupplier.get());
    }

    public static MutablePropertySources getMutablePropertySources() {
        return configurableEnvironment.getPropertySources();
    }

    public static void addFirst(PropertySource<?> propertySource) {
        getMutablePropertySources().addFirst(propertySource);
    }

    public static void addLast(PropertySource<?> propertySource) {
        getMutablePropertySources().addLast(propertySource);
    }

    private static void initConfigurableEnvironment(ApplicationContext context) {
        if (Objects.isNull(configurableEnvironment)) {
            synchronized (SpringEnvironmentHelper.class) {
                if (Objects.isNull(configurableEnvironment)) {
                    configurableEnvironment = context.getBean(ConfigurableEnvironment.class);
                }
            }
        }
    }

    @Override
    protected void initApplicationContext(ApplicationContext context) throws BeansException {
        initConfigurableEnvironment(context);
    }
}
